Page({
  data: {
    userInfo: {},
    // 被收藏的商品数量
    collectedNums: 0,
    avatarUrl: '../../icons/y3.png',
    serve: [],
    goods: []
  },
  onLoad() {
    wx.showLoading({
      title: '加载中',
    })
    const userInfo = wx.getStorageSync('userInfo');
    const collect = wx.getStorageSync('collect');
    const serve = wx.getStorageSync('serve');
    const goods = wx.getStorageSync('goods');
    if(!serve) {
      this.getServe()
    } else {
      this.setData({
        serve
      })
    }
    this.setData({
      userInfo,
      collectedNums: collect.length,
      goods
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1500)
  },
  getServe() {
    wx.cloud.database().collection("myown")
   .get()
   .then(res => {
     console.log(res);
     this.setData({
      serve: res.data
     })
     wx.setStorageSync('serve', this.data.serve)
   })
  },
  // 添加头像
  addAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        console.log(tempFilePaths);
        this.uploadFile(tempFilePaths, this.data.userInfo._id) 
      },
    })
  },
  //上传操作
  uploadFile(filePath, id) {
    let that = this;
    wx.cloud.uploadFile({
      cloudPath: 'bishe/' + (new Date()).valueOf() + '.png', // 文件名
      filePath: filePath, // 文件路径
      success: res => {
        console.log(res.fileID)
        wx.cloud.database().collection("userInfo").doc(id)
        .update({
          data: {
            avatar: res.fileID
          }
        })
        .then(res => {
          console.log('上传成功',res);
        })
        wx.cloud.database().collection("userInfo").doc(id)
        .get()
        .then(res => {
          console.log('获取上传成功',res);
          this.setData({
            userInfo: res.data
          })
          wx.setStorageSync('userInfo', this.data.userInfo)
          that.onLoad()
        })
      },
      fail: err => {
        console.log(err);
      }
    })
  }
})